﻿using Microsoft.AspNetCore.Mvc.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace iTool.Validator
{

    /// <summary>
    /// 方法信息缓存类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ValidatorMethodsInfoCache
    {
        

        static IDictionary<int,MethodInfo> methodsInfo = new Dictionary<int,MethodInfo>();


        static ValidatorMethodsInfoCache()
        {

            var types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(a => a.GetTypes().Where(t => t.BaseType == typeof(ControllerValidatorAttribute)))
                .ToArray();

            foreach (var item in types)
            {
                CreateMethodsInfoDictionary(item);
            }
            
        }

        /// <summary>
        /// 创建方法属性字典
        /// </summary>
        static void CreateMethodsInfoDictionary(Type type)
        {
            var typeName = type.Name;

            foreach (var method in type.GetMethods()) if (ValidatorUtils.GetMethodIsNotFilterList(method))
            {
               var cacheKey =  ValidatorUtils.GetMethodCacheKeyByMethod(method);
               int keyCode = (typeName + "_" + cacheKey).GetHashCode();
               methodsInfo.Add(keyCode, method);
            }

        }

        /// <summary>
        /// 根据Action描述信息 获取验证方法
        /// </summary>
        /// <param name="action">Action描述信息</param>
        /// <returns></returns>
        public static MethodInfo GetMethod(ActionDescriptor action, Type type)
        {
            var cacheKey = ValidatorUtils.GetMethodCacheKeyByControllerActionDescriptor(action);

            var typeName = type.Name;

            int keyCode = (typeName + "_" + cacheKey).GetHashCode();

            methodsInfo.TryGetValue(keyCode, out MethodInfo method);

            return method;
        }

    }
}
